<template>
  <div class="address-manage">
    <van-nav-bar
      title="地址管理"
      left-arrow
      @click-left="goBack"
      fixed
    />
    
    <div class="content">
      <div v-if="addresses.length > 0" class="address-list">
        <div 
          v-for="address in addresses" 
          :key="address.id" 
          class="address-item"
          :class="{'address-item--selected': address.isDefault}"
        >
          <div class="address-info">
            <div class="address-header">
              <span class="name">{{ address.name }}</span>
              <span class="phone">{{ maskPhone(address.phone) }}</span>
              <span class="tag" :class="`tag-${address.type}`">{{ getAddressTypeText(address.type) }}</span>
            </div>
            <div class="address-content">
              {{ formatAddress(address) }}
            </div>
            <div class="address-action" v-if="address.isDefault">
              <van-checkbox v-model="address.isDefault" :disabled="true" shape="square">设为默认地址</van-checkbox>
            </div>
          </div>
          <div class="address-operations">
            <span class="edit" @click="onEdit({id: address.id}, 0)">编辑</span>
            <span class="delete" @click="deleteAddress(address.id)">删除</span>
          </div>
        </div>
      </div>
      
      <div v-else class="empty-tips">
        <p>暂无收货地址，请添加</p>
      </div>
      
      <div class="add-address">
        <van-button type="primary" block round @click="addNewAddress">
          <van-icon name="plus" /> 新增收货地址
        </van-button>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, onMounted, computed } from 'vue';
import { useRouter } from 'vue-router';
import api from '../network/api';
import { showToast, showDialog } from 'vant';

// 定义地址接口
interface Address {
  id: number;
  name: string;
  phone: string;
  provinceCode: string;
  provinceName: string;
  cityCode: string;
  cityName: string;
  districtCode: string;
  districtName: string;
  streetCode: string;
  streetName: string;
  detail: string;
  type: string;
  isDefault: boolean;
}

// 静态地址数据
const staticAddresses: Address[] = [
  {
    id: 1,
    name: '王小明',
    phone: '13888888888',
    provinceCode: '110000',
    provinceName: '北京市',
    cityCode: '110100',
    cityName: '北京市',
    districtCode: '110105',
    districtName: '朝阳区',
    streetCode: '110105001',
    streetName: '建国门街道',
    detail: '中央公园1号楼2单元502室',
    type: 'home',
    isDefault: true
  },
  {
    id: 2,
    name: '王小明',
    phone: '13888888888',
    provinceCode: '110000',
    provinceName: '北京市',
    cityCode: '110100',
    cityName: '北京市',
    districtCode: '110108',
    districtName: '海淀区',
    streetCode: '110108001',
    streetName: '中关村街道',
    detail: '创业大厦15层1503室',
    type: 'company',
    isDefault: false
  },
  {
    id: 3,
    name: '王小明',
    phone: '13888888888',
    provinceCode: '110000',
    provinceName: '北京市',
    cityCode: '110100',
    cityName: '北京市',
    districtCode: '110102',
    districtName: '西城区',
    streetCode: '110102001',
    streetName: '西单街道',
    detail: '西单商场南街18号2号楼1单元801室',
    type: 'other',
    isDefault: false
  }
];

export default defineComponent({
  name: 'AddressManageView',
  
  setup() {
    const router = useRouter();
    const addresses = ref<Address[]>([]);
    const defaultAddressId = ref<string | number>('');
    const useStaticData = true; // 是否使用静态数据
    
    // 获取地址列表
    const getAddresses = async () => {
      try {
        if (useStaticData) {
          // 使用静态数据
          addresses.value = [...staticAddresses];
          
          // 设置默认地址ID
          const defaultAddress = addresses.value.find((addr: Address) => addr.isDefault);
          if (defaultAddress) {
            defaultAddressId.value = defaultAddress.id;
          }
        } else {
          // 使用API接口获取数据
          const response = await api.getUserAddresses();
          addresses.value = response.data;
          
          // 设置默认地址ID
          const defaultAddress = addresses.value.find((addr: Address) => addr.isDefault);
          if (defaultAddress) {
            defaultAddressId.value = defaultAddress.id;
          }
        }
      } catch (error) {
        console.error('获取地址列表失败', error);
        showToast('获取地址列表失败');
      }
    };
    
    // 设置默认地址
    const setDefault = async (addressId: number) => {
      try {
        if (!useStaticData) {
          await api.setDefaultAddress(addressId);
        }
        
        // 更新本地数据
        addresses.value = addresses.value.map((address: Address) => ({
          ...address,
          isDefault: address.id === addressId
        }));
        
        showToast('设置成功');
      } catch (error) {
        console.error('设置默认地址失败', error);
        showToast('设置默认地址失败');
      }
    };
    
    // 地址选择事件
    const onSelect = (addressId: number) => {
      setDefault(addressId);
    };
    
    // 编辑地址事件
    const onEdit = (item: {id: number}, index: number) => {
      editAddress(Number(item.id));
    };
    
    // 编辑地址
    const editAddress = (addressId: number) => {
      router.push(`/address/edit/${addressId}`);
    };
    
    // 删除地址
    const deleteAddress = async (addressId: number) => {
      try {
        await showDialog({
          title: '确认删除',
          message: '确定要删除该地址吗？',
          showCancelButton: true,
        });
        
        if (!useStaticData) {
          await api.deleteAddress(addressId);
        }
        
        // 从本地数据中移除
        addresses.value = addresses.value.filter((address: Address) => address.id !== addressId);
        showToast('删除成功');
      } catch (error) {
        if (error === 'cancel') return; // 用户取消操作
        
        console.error('删除地址失败', error);
        showToast('删除地址失败');
      }
    };
    
    // 新增地址
    const addNewAddress = () => {
      router.push('/address/add');
    };
    
    // 返回上一页
    const goBack = () => {
      router.back();
    };
    
    // 电话号码脱敏处理
    const maskPhone = (phone: string) => {
      if (!phone || phone.length < 11) return phone;
      return phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
    };
    
    // 获取地址类型文本
    const getAddressTypeText = (type: string) => {
      const typeMap: Record<string, string> = {
        'home': '家',
        'company': '公司',
        'other': '其他'
      };
      return typeMap[type] || '其他';
    };
    
    // 格式化地址
    const formatAddress = (address: Address) => {
      return `${address.provinceName}${address.cityName}${address.districtName}${address.streetName}${address.detail}`;
    };
    
    onMounted(() => {
      getAddresses();
    });
    
    return {
      addresses,
      defaultAddressId,
      setDefault,
      editAddress,
      deleteAddress,
      addNewAddress,
      goBack,
      maskPhone,
      getAddressTypeText,
      formatAddress,
      onEdit,
      onSelect
    };
  }
});
</script>

<style scoped>
.address-manage {
  background-color: #f5f5f5;
  min-height: 100vh;
}

.content {
  padding-top: 46px; /* 导航栏高度 */
  padding-bottom: 80px; /* 底部按钮区域高度 */
}

.address-item {
  background-color: #fff;
  margin: 10px;
  padding: 15px;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0,0,0,0.1);
  position: relative;
}

.address-item--selected {
  border: 1px solid #3490dc;
}

.address-header {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.name {
  font-size: 16px;
  font-weight: 500;
  margin-right: 10px;
}

.phone {
  color: #666;
}

.tag {
  margin-left: auto;
  padding: 2px 8px;
  border-radius: 10px;
  font-size: 12px;
  color: #fff;
  background-color: #3490dc;
}

.tag-home {
  background-color: #3490dc;
}

.tag-company {
  background-color: #4caf50;
}

.tag-other {
  background-color: #ff9800;
}

.address-content {
  color: #333;
  font-size: 14px;
  line-height: 1.5;
  padding-right: 20px;
  margin-bottom: 10px;
}

.address-action {
  display: flex;
  align-items: center;
  color: #666;
  font-size: 13px;
}

.address-operations {
  display: flex;
  justify-content: flex-end;
  margin-top: 10px;
  padding-top: 10px;
  border-top: 1px solid #eee;
}

.edit, .delete {
  font-size: 14px;
  color: #666;
  padding: 5px 15px;
  cursor: pointer;
}

.edit {
  border-right: 1px solid #eee;
}

.empty-tips {
  text-align: center;
  padding: 30px 0;
  color: #999;
}

.add-address {
  position: fixed;
  bottom: 20px;
  left: 15px;
  right: 15px;
}

:deep(.van-button--primary) {
  background-color: #3490dc;
  border-color: #3490dc;
}
</style> 